﻿using System.Collections.Generic;
using AutoMapper;
using B.S.DataBase.MyProject.Domain.Procurements;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Write.API.Applicantions.Command.ProcurementsCommand;
using Yitter.IdGenerator;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler.ProcurementsCommandCommand
{
    /// <summary>
    /// 采购订单编辑
    /// </summary>
    public class UpdatePurcersCommandHandler : IRequestHandler<UpdatePurcersCommand, APIResult<object>>
    {

        /// <summary>
        /// 采购订单表
        /// </summary>
        private readonly IBaseRepository<Purchaseorder> baseRepository;



        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseRepository"></param>
        public UpdatePurcersCommandHandler(IBaseRepository<Purchaseorder> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<object>> Handle(UpdatePurcersCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var add = baseRepository.GetAll().Result.Where(X => X.PurchaseOrderId == request.PurchaseOrderId).FirstOrDefault();
            add.PurchaseOrderId = request.PurchaseOrderId;
            add.DocumentCode = request.DocumentCode;
            add.DocumentStatus = request.DocumentStatus;
            add.BusinessStatus = request.BusinessStatus;//
            add.BusinessType = request.BusinessType;
            add.Documentid = request.Documentid;
            add.PurchasingDe = request.PurchasingDe;
            add.Purchasingid = request.Purchasingid;
            add.Operator = request.Operator;
            add.Auditor = request.Auditor;
            add.AuditDate = request.AuditDate;
            add.MaterialData = request.MaterialData;
            add.MaterialRire = request.MaterialRire;
            add.Supid = request.Supid;//
            add.ArrivalDate = request.ArrivalDate;
            add.PurchaseContract = request.PurchaseContract;
            add.RemarksInfor = request.RemarksInfor;


            int t  =  baseRepository.Update(add).Result;
            if(t>0)
            {
                request.materials_Infos.ForEach(x =>
                {
                    x.SaleCode = add.DocumentCode;

                });
                result.Code = APIEnum.修改成功;
                result.Msg = APIEnum.修改成功.ToString();
                result.data = t;
            }
            else
            {
                result.Code = APIEnum.修改失败;
                result.Msg = APIEnum.修改失败.ToString();
            }

            return Task.FromResult(result);
        }
    }
}
